//
//  XWHearingOrAidGainsChartView.swift
//  XWHAOfflineFitting
//
//  Created by edy on 2024/11/19.
//

import UIKit
import Charts

/**
    与 XWHAOFHearingChartLineChartView 相似 应用在小维妙音App中
 */
class XWHearingOrAidGainsChartView: AppLineChartView {

    private(set) lazy var iconView = UIImageView()
    
    private(set) lazy var freqBandList: [Int] = []
    
    var isLeft = true
    
    var maxValue: Double {
        15
    }
    var minValue: Double {
        -15
    }
    
    var volumeUnitText: String {
        "dB"
    }
    
    override func addSubViews() {
        super.addSubViews()
        
        addSubview(iconView)
        
        layer.cornerRadius = 16
        layer.backgroundColor = collectionBgColor.cgColor
    }
    
    override func relayoutSubViews() {
        iconView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.width.equalTo(67)
            make.top.equalToSuperview()
            make.height.equalTo(24)
        }
        chartView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(iconView.snp.bottom).offset(4)
            make.bottom.equalToSuperview().inset(8)
        }
    }
    
    func updateChart(gainList: [XWHAFrequencyBandRecordModel]) {
        var lineColor: UIColor
        var markerBg: UIImage?
        
        var dotImage: UIImage?
        var chartTipIconName: String = ""
        if isLeft {
            lineColor = UIColor(hex: 0x007EFF)!
            
            chartTipIconName = "left_ear_chart_tip_icon"
            
//            markerBg = R.image.left_chart_marker_bg()
            var mBgImage = UIImage(named: "left_chart_wdrc_marker_bg")
            if mBgImage == nil {
                mBgImage = UIImage(named: "left_chart_marker_bg")
            }
            markerBg = mBgImage
            
            dotImage = R.image.ac_no_mask_l_icon()
        } else {
            lineColor = UIColor(hex: 0xFF5D34)!
            
            chartTipIconName = "right_ear_chart_tip_icon"

            var mBgImage = UIImage(named: "right_chart_wdrc_marker_bg")
            if mBgImage == nil {
                mBgImage = UIImage(named: "right_chart_marker_bg")
            }
            markerBg = mBgImage
            dotImage = R.image.ac_no_mask_r_icon()
        }
        
        let lang = AppFunctionHelper.getLocalPrimaryLanguage()
        if lang != "zh" {
            chartTipIconName += "_en"
        }
        
        iconView.image = UIImage(named: chartTipIconName)
        markerView.image = markerBg
        
        freqBandList = gainList.map({ $0.freqBand })
        configXAxis()
        
        var acDataEntries = [ChartDataEntry]()
        for (_, iItem) in gainList.enumerated() {
            if let tIndex = freqBandList.firstIndex(where: { $0 == iItem.freqBand }) {
                let value = max(min(maxValue, iItem.value), minValue)
                let entry = ChartDataEntry.init(x: Double(tIndex), y: value)
                entry.icon = dotImage
                acDataEntries.append(entry)
            }
        }
        
        let acChartDataSet = LineChartDataSet(entries: acDataEntries, label: nil)
        config(chartDataSet: acChartDataSet, lineColor: lineColor)
        acChartDataSet.lineWidth = 2
        
        var dataSets: [LineChartDataSet] = []
        dataSets.append(acChartDataSet)
        
        //目前折线图只包括1根折线
        let chartData = LineChartData(dataSets: dataSets)
        
        //设置折现图数据
        chartView.data = chartData
    }
    
    private func config(chartDataSet: LineChartDataSet, lineColor: UIColor) {
        //        chartDataSet.highlightEnabled = false
        chartDataSet.drawVerticalHighlightIndicatorEnabled = false
        chartDataSet.drawHorizontalHighlightIndicatorEnabled = false
        chartDataSet.drawValuesEnabled = false
        chartDataSet.drawCirclesEnabled = false
        chartDataSet.drawCircleHoleEnabled = false
        chartDataSet.mode = .linear
        chartDataSet.setColor(lineColor)
        
        //开启填充色绘制
        chartDataSet.drawFilledEnabled = false
//        let gradientColors = [lineColor.cgColor, UIColor.white.cgColor] as CFArray
//        //每组颜色所在位置（范围0~1)
//        let colorLocations:[CGFloat] = [1.0, 0.0]
//        //生成渐变色
//        if let gradient = CGGradient.init(colorsSpace: CGColorSpaceCreateDeviceRGB(),
//                                          colors: gradientColors, locations: colorLocations) {
//            //将渐变色作为填充对象s
//            chartDataSet.fill = Fill.fillWithLinearGradient(gradient, angle: 90)
//            chartDataSet.fillFormatter = DefaultFillFormatter(block: { dataSet, dataProvider in
//                CGFloat(self.chartView.leftAxis.axisMaximum)
//            })
//        }
    }

}

extension XWHearingOrAidGainsChartView {
    
    override func configXAxis() {
        chartView.maxVisibleCount = 1000
        
        chartView.xAxis.labelPosition = .bottom
        
        let xMaxValue = freqBandList.count - 1
        chartView.xAxis.axisMaxLabels = xMaxValue + 1
        
        chartView.xAxis.axisMinimum = 0
        chartView.xAxis.granularity = 1
        chartView.xAxis.axisMaximum = Double(xMaxValue)
        
        chartView.xAxis.labelCount = chartView.xAxis.axisMaxLabels
        chartView.xAxis.forceLabelsEnabled = true
//        chartView.xAxis.granularityEnabled = true
        
        chartView.xAxis.axisLineWidth = 1
        chartView.xAxis.axisLineColor = UIColor.black.withAlphaComponent(0.05)
        chartView.xAxis.drawAxisLineEnabled = true
        
        chartView.xAxis.gridLineWidth = 1
        chartView.xAxis.gridColor = UIColor.black.withAlphaComponent(0.05)
        chartView.xAxis.drawGridLinesEnabled = true
        
        chartView.xAxis.labelFont = AppFont.harmonyOSSans(ofSize: 10)
        chartView.xAxis.labelTextColor = minorTextColor
        chartView.xAxis.valueFormatter = DefaultAxisValueFormatter(block: { [weak self] value, _ in
            let x = value.int
            var ret = x.string
            guard let self = self else {
                return ret
            }
            
            ret = self.getXValue(xIndex: x)
            
            return ret
        })
    }
    
    func getXValue(xIndex: Int) -> String {
        var ret = xIndex.string
        if xIndex < self.freqBandList.count, xIndex >= 0 {
            let tBand = self.freqBandList[xIndex]
            ret = AppFunctionHelper.getShortFreqBandText(freqBand: tBand)
        }
        
        return ret
    }
    
    override func configYAxis() {
        //        chartView.leftAxis.enabled = false
        
        let axisMinimum: Double = minValue
        let axisMaximum: Double = maxValue
        let labelCount = (axisMaximum.int - (axisMinimum.int)) + 1
        let granularity: Double = 1
        let isInverted = false
        chartView.leftAxis.inverted = isInverted
        chartView.leftAxis.axisMinimum = axisMinimum
        chartView.leftAxis.axisMaximum = axisMaximum
        chartView.leftAxis.granularity = granularity
        chartView.leftAxis.setLabelCount(labelCount, force: true)
        
        chartView.rightAxis.inverted = isInverted
        chartView.rightAxis.axisMinimum = axisMinimum
        chartView.rightAxis.axisMaximum = axisMaximum
        chartView.rightAxis.granularity = granularity
        chartView.rightAxis.setLabelCount(labelCount, force: true)
        
        let lineColor = UIColor.black.withAlphaComponent(0.05)
        let lineWidth = 0.5
        chartView.leftAxis.axisLineColor = lineColor
        chartView.leftAxis.axisLineWidth = lineWidth
        
        chartView.rightAxis.axisLineColor = lineColor
        chartView.rightAxis.axisLineWidth = lineWidth
        
        chartView.leftAxis.drawGridLinesEnabled = true
        chartView.leftAxis.drawLabelsEnabled = true
        
        chartView.rightAxis.drawGridLinesEnabled = false
        chartView.rightAxis.drawLabelsEnabled = false
        
        chartView.leftAxis.axisLineColor = lineColor
        chartView.leftAxis.axisLineWidth = lineWidth
        
        chartView.leftAxis.gridLineWidth = lineWidth
        chartView.leftAxis.gridColor = lineColor
        
        chartView.rightAxis.gridLineWidth = lineWidth
        chartView.rightAxis.gridColor = lineColor
        
        chartView.leftAxis.labelFont = AppFont.harmonyOSSans(ofSize: 10)
        chartView.leftAxis.labelTextColor = minorTextColor
        
        chartView.rightAxis.labelFont = AppFont.harmonyOSSans(ofSize: 10)
        chartView.rightAxis.labelTextColor = minorTextColor
        
        chartView.leftAxis.valueFormatter = DefaultAxisValueFormatter(block: { [weak self] value, _ in
//            let y = value.int / 10
            var ret = ""
            guard let _ = self else {
                return ret
            }
            
//            if y % 2 == 0 {
//                ret = value.int.string
//            } else {
//                ret = ""
//            }
            ret = value.int.string
            
            return ret
        })
    }
    
}

// MARK: - ChartViewDelegate
extension XWHearingOrAidGainsChartView {
    
    override func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
        guard let dataSet = chartView.data?.dataSets[highlight.dataSetIndex] else { return }
        
        //        markerView.setShowOffset(chartView, entry: entry, highlight: highlight)
        ////        let entryIndex = dataSet.entryIndex(entry: entry)
        //        markerView.textLb.text =  .string
        //        markerView.detailLb.text = entry.y.int.string
        
        let x = entry.x.int
        let y = entry.y.int
        
        let ret = getXValue(xIndex: x)
        
        var title = ""
        if let dLabel = dataSet.label {
            title = dLabel + "\n"
        }
        markerView.setLabel("\(title)\(ret)Hz/\(y.string)\(volumeUnitText)")
    }
    
}

